package com.zhilong;

import java.util.ArrayList;
import java.util.List;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.protocol.HTTP;
import org.json.JSONObject;

import android.app.Activity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Toast;

import com.tencent.tauth.IUiListener;
import com.tencent.tauth.Tencent;
import com.tencent.tauth.UiError;
import com.zhiyun.R;


public class MainActivity extends Activity {
    
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        
        findViewById(R.id.btnGuestTour).setOnClickListener(new View.OnClickListener() 
        {
			@Override
			public void onClick(View view) {
				startActivity(new Intent(view.getContext(), GuestCampaignActivity.class));
			}
        });

        findViewById(R.id.btnJoinCampaign).setOnClickListener(new View.OnClickListener() 
        {
			@Override
			public void onClick(View view) {
				if(!SessionMgr.getCurrentSession().isLoggedIn())
				{
					SessionMgr.getCurrentSession().login(MainActivity.this);
				}
				else
					startActivityForResult(new Intent(view.getContext(), CompetitionCampaignActivity.class), 0);
			}
        });
        
        findViewById(R.id.btnSubmitQuestion).setOnClickListener(new View.OnClickListener() 
        {
			@Override
			public void onClick(View view) {
				startActivity(new Intent(view.getContext(), SubmitQuestion.class));
			}
        });
        
        findViewById(R.id.btnShowUserPoint).setOnClickListener(new View.OnClickListener() 
        {
			@Override
			public void onClick(View view) {
				if(!SessionMgr.getCurrentSession().isLoggedIn())
				{
					SessionMgr.getCurrentSession().login(MainActivity.this);
				}
				else
					startActivity(new Intent(view.getContext(), ShowUserPoint.class));
			}
        });
        
        findViewById(R.id.btnSettings).setOnClickListener(new View.OnClickListener() 
        {
			@Override
			public void onClick(View view) {
				startActivity(new Intent(view.getContext(), Settings.class));
			}
        });
        
        
        findViewById(R.id.btnExit).setOnClickListener(new View.OnClickListener() 
        {
			@Override
			public void onClick(View view) {
				MainActivity.this.finish();
			}
        });
    }
    
	private static final String PREFS_NAME = "ZhilongPrefs";
    private void init()
    {
		SharedPreferences settings = getSharedPreferences(PREFS_NAME, 0);
		String server = settings.getString("server", "");
    	
		GlobalSettings.setServer(server);
    }
    
    @Override
    public void onDestroy()
    {
    	super.onDestroy();
    	logout();
    }
    
 	private void logout()
	{
		new WebTask(this){
	        protected String doInBackground(String...urls) 
	        {
	        	if(!SessionMgr.getCurrentSession().isLoggedIn())
	        		return "SUCCESS";
	        	
	    		try{
					HttpClient client = new DefaultHttpClient();
		    		HttpPost request = new HttpPost(urls[0]);
		    		HttpResponse response = null;
					request.setHeader("Content-type", "application/x-www-form-urlencoded");

					String sessionId = SessionMgr.getCurrentSession().getId(); 
					if(null != sessionId){
						request.setHeader("Cookie", "JSESSIONID=" + sessionId);
			        }

					Log.i(getClass().getName(), "logout");
					List<NameValuePair> params = new ArrayList<NameValuePair>();
					params.add(new BasicNameValuePair("op", "logout"));
					HttpEntity httpEntity = new UrlEncodedFormEntity(params, HTTP.UTF_8);
					request.setEntity(httpEntity);
					response = client.execute(request);
					Log.i(getClass().getName(), "login succeed");
					int ret = response.getStatusLine().getStatusCode(); 
					if (ret != HttpStatus.SC_OK) {
				          Log.e(getClass().getName(), "Fail to access the url, return code " + ret);
				          return "FAIL";
				    }
	    		}catch(Exception ex)
	    		{
	    			Log.e(getClass().getName(), "Fail to login");
	        		return "FAIL";
	    		}
        		return "SUCCESS";
	        }
			
	        protected void onPostExecute(String result) {
	        	if("SUCCESS".equals(result))
	        	{
					SessionMgr.getCurrentSession().setLoggedIn(false);
					SessionMgr.getCurrentSession().setUid(0);
	        	}
	        }
		}.execute(GlobalSettings.getServerHttpUrl() + "/Logon");
	}

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) 
	{
    	super.onActivityResult(requestCode, resultCode, data);
    	
    	if(data == null) return;
    	
    	String action = data.getStringExtra("action");
    	Log.i(getClass().getName(), "Action after login: " + action);
    	
    	if("showUserPoint".equals(action))
    		startActivity(new Intent(this, ShowUserPoint.class));
    	else if("joinCampaign".equals(action))
			startActivity(new Intent(this, CompetitionCampaignActivity.class));
	}
}
